<template>
  <j-modal
    title="结算记录"
    :width="900"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="loading">
      <!-- 订单信息 -->
      <div class="bill-header">
        <div class="bill-info">
          <p><strong>订单名称：</strong>{{ orderInfo.orderName }}</p>
          <p><strong>程序员：</strong>{{ orderInfo.programmerName }}</p>
          <p><strong>联系电话：</strong>{{ orderInfo.phone || '未知' }}</p>
          <p><strong>订单金额：</strong>{{ orderInfo.orderAmount ? orderInfo.orderAmount.toFixed(2) : '0.00' }} 元</p>
          <p><strong>抽成比例：</strong>{{ orderInfo.commissionRate ? orderInfo.commissionRate + '%' : '0%' }}</p>
          <p><strong>程序员应得：</strong>{{ programmerAmount }} 元</p>
          <p><strong>已结算金额：</strong>{{ totalBillAmount }} 元</p>
          <p><strong>剩余结算金额：</strong>{{ remainingAmount }} 元</p>
          <p v-if="billTypeStats.length > 0"><strong>结算类型统计：</strong>
            <span v-for="(item, index) in billTypeStats" :key="index" style="margin-right: 10px;">
              {{ item.text }}：{{ item.amount.toFixed(2) }} 元
            </span>
          </p>
        </div>
        <div class="bill-actions">
          <a-button type="primary" @click="handleAdd">添加结算</a-button>
        </div>
      </div>
      
      <!-- 结算记录表格 -->
      <a-table
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        rowKey="id"
        size="middle">
        
        <!-- 结算类型 -->
        <template slot="billTypeSlot" slot-scope="text">
          <j-dict-select-tag :value="text" dictCode="bill_type" disabled />
        </template>
        
        <!-- 支付方式 -->
        <template slot="paymentMethodSlot" slot-scope="text">
          <j-dict-select-tag :value="text" dictCode="payment_method" disabled />
        </template>
        
        <!-- 操作按钮 -->
        <template slot="actionSlot" slot-scope="text, record">
          <a @click="handleEdit(record)" style="margin-right: 8px">编辑</a>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-spin>
    
    <!-- 结算模态框 -->
    <b-programmer-bill-modal ref="billModalForm" @ok="loadData"></b-programmer-bill-modal>
  </j-modal>
</template>

<script>
  import { getAction, deleteAction } from '@/api/manage'
  import BProgrammerBillModal from './BProgrammerBillModal'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'
  
  export default {
    name: "BProgrammerBillListModal",
    components: {
      BProgrammerBillModal,
      JDictSelectTag
    },
    data() {
      return {
        visible: false,
        loading: false,
        orderInfo: {
          id: '',
          orderName: '',
          programmerId: '',
          programmerName: '',
          phone: '',
          orderAmount: 0,
          commissionRate: 0
        },
        // 表格列定义
        columns: [
          {
            title: '结算金额',
            dataIndex: 'billAmount',
            align: 'right',
            customRender: (text) => {
              return text ? text.toFixed(2) + ' 元' : '0.00 元';
            }
          },
          {
            title: '结算类型',
            dataIndex: 'billType',
            scopedSlots: { customRender: 'billTypeSlot' }
          },
          {
            title: '支付方式',
            dataIndex: 'paymentMethod',
            scopedSlots: { customRender: 'paymentMethodSlot' }
          },
          {
            title: '结算日期',
            dataIndex: 'billDate',
            width: 180,
            customRender: (text) => {
              return text ? text.substring(0, 10) : '';
            }
          },
          {
            title: '备注',
            dataIndex: 'remarks'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: 100,
            align: 'center',
            scopedSlots: { customRender: 'actionSlot' }
          }
        ],
        // 数据源
        dataSource: [],
        // 分页配置
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条";
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        url: {
          list: '/order/bProgrammerBillInfo/queryListByOrderId',
          delete: '/order/bProgrammerBillInfo/delete'
        }
      }
    },
    computed: {
      // 计算程序员应得金额
      programmerAmount() {
        if (!this.orderInfo.orderAmount || !this.orderInfo.commissionRate) {
          return '0.00';
        }
        const amount = Number(this.orderInfo.orderAmount) * (1 - Number(this.orderInfo.commissionRate) / 100);
        return amount.toFixed(2);
      },
      
      // 计算总结算金额
      totalBillAmount() {
        let total = 0;
        this.dataSource.forEach(item => {
          total += Number(item.billAmount || 0);
        });
        return total.toFixed(2);
      },
      
      // 计算剩余结算金额
      remainingAmount() {
        const programmerAmount = Number(this.programmerAmount);
        const totalBillAmount = Number(this.totalBillAmount);
        const remaining = programmerAmount - totalBillAmount;
        return remaining > 0 ? remaining.toFixed(2) : '0.00';
      },
      
      // 计算各结算类型的统计
      billTypeStats() {
        // 创建一个Map来存储每种结算类型的总金额
        const typeMap = new Map();
        
        // 遍历所有结算记录
        this.dataSource.forEach(item => {
          if (!item.billType || !item.billAmount) return;
          
          const billType = item.billType;
          const amount = Number(item.billAmount || 0);
          
          if (typeMap.has(billType)) {
            // 如果已存在该类型，累加金额
            typeMap.set(billType, typeMap.get(billType) + amount);
          } else {
            // 否则创建新记录
            typeMap.set(billType, amount);
          }
        });
        
        // 转换为数组格式，并获取字典文本
        const result = [];
        typeMap.forEach((amount, type) => {
          // 尝试从缓存中获取字典文本
          let text = this.getDictText('bill_type', type);
          if (!text) text = type; // 如果没有找到文本，使用类型值
          
          result.push({
            type,
            text,
            amount
          });
        });
        
        return result;
      }
    },
    methods: {
      // 获取字典文本
      getDictText(dictCode, value) {
        // 如果没有值，返回空字符串
        if (!value) return '';
        
        // 从缓存中获取字典项
        const dictItems = getDictItemsFromCache(dictCode);
        if (dictItems) {
          const dictItem = dictItems.find(item => item.value === value);
          return dictItem ? dictItem.text : value;
        }
        
        // 如果缓存中没有，返回原始值
        return value;
      },
      
      // 显示模态框
      show(record) {
        this.visible = true;
        this.orderInfo = {
          id: record.id,
          orderName: record.orderName,
          programmerId: record.programmerId,
          programmerName: record.programmerName || '未知',
          phone: record.phone || '',
          orderAmount: record.orderAmount || 0,
          commissionRate: record.commissionRate || 0
        };
        this.loadData();
      },
      
      // 加载结算记录数据
      loadData() {
        this.loading = true;
        
        // 查询参数
        let params = {
          orderId: this.orderInfo.id,
          pageNo: this.ipagination.current,
          pageSize: this.ipagination.pageSize
        };
        
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 添加结算记录
      handleAdd() {
        this.$refs.billModalForm.show(this.orderInfo);
      },
      
      // 编辑结算记录
      handleEdit(record) {
        this.$refs.billModalForm.show(this.orderInfo, record);
      },
      
      // 删除结算记录
      handleDelete(id) {
        this.loading = true;
        deleteAction(this.url.delete, { id: id }).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.loadData();
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 取消按钮点击
      handleCancel() {
        this.visible = false;
      }
    }
  }
</script>

<style scoped>
  .bill-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background-color: #f8f8f8;
    border-radius: 4px;
  }
  
  .bill-info p {
    margin-bottom: 8px;
  }
  
  .bill-info p:last-child {
    margin-bottom: 0;
  }
</style> 